<?php


namespace App\Repositories\Game\Lucky;

use App\Models\GameDB\LuckyStrike\RebateUser as model;
use App\Traits\Singleton;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class StrikeUserRepositories
{
    use Singleton;

    public function userBalance(int $userId): int
    {
        $query = model::query();
        $query->where("user_id", $userId);
        $balance = $query->value("balance");
        return (int)$balance;
    }

    public function automatic(int $userId, $automatic): int
    {
        $user = $this->user($userId,true,true);
        if (!$user || $user->id == 0) {
            $user = $this->create(["user_id" => $userId, "automatic" => $automatic]);
            return $user->id;
        }


        //decrement  减少  increment 增加
        return  model::query()->where('user_id',$userId)->update(["automatic" => $automatic]);
        //return $this->update($userId, ["balance" => DB::raw("`balance` + $count")]);
    }

    public function swap(int $userId, int $count): int
    {

        $user = $this->user($userId,true,true);
        if (!$user || $user->id == 0) {
            $user = $this->create(["user_id" => $userId, "balance" => $count]);
            return $user->id;
        }
        //decrement  减少  increment 增加
        return model::query()->where('id',$user->id)->increment("balance",$count);
        //return $this->update($userId, ["balance" => DB::raw("`balance` + $count")]);
    }

    public function user(int $userId, $isLock = false, $type = false )
    {
        $query = Model::query();
        if ($isLock) {
            $query->lockForUpdate();
        }
        $query->where("user_id", $userId);
        if ($type) {
            return $query->first();
        }
        $query->with([
            "date" => function ($query) {
                $query->where('date', '=', Carbon::now()->format("Y-m-d"));
                $query->select(["date", "user_id", "count", "input", "output"]);
            }
        ]);
        $model = $query->first();
        if (!$model) {
            $model          = new Model();
            $model->id      = 0;
            $model->user_id = $userId;
            $model->balance = 0;
            $model->input   = 0;
            $model->output  = 0;
        }
        return $model;
    }
    // 新增用户 钱包金币
    public function create(array $data): Model
    {
        $model = new Model();
        $model->fill($data);
        $model->save();
        $model->refresh();

        return $model;
    }
    // 新增用户 钱包金币
    public function updateByCondition(array $condition, array $data): int
    {
        $query = Model::query();
        $query->where($condition);
        return $query->update($data);
    }
    // 修改用户 钱包金币
    public function update(int $id, array $data): int
    {
        return $this->updateByCondition(['id' => $id], $data);
    }
}
